﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    export class AddEditSubscriptionController {

        //public select

        public selectedPortfolios: { id: string; }[];
        public allPortfolios: { id: string; label: string; group: string }[];
        public portfolioGroupingSettings: any;
        private userId: string;
        private accountId: string;
        private isAdd: boolean;
        private oldItem: SubscribeToPortfolio;
        private clickSave: boolean;
        private $routeParams: any;
        private hasSemimonthlyClaim: boolean;
        //private hasMonthlyClaim: boolean;
        //private hasQuarterlyClaim: boolean;
        private hasEditPermission: boolean;
        public sharedPortfolios: boolean;
        public myEvents: any;
        public static allCompaniesLabel : string = "All companies";

        // Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private SubscribeToPortfolioService: SubscribeToPortfolioService,
            private notificationFactory: Common.INotificationFactory,
            private $modalInstance: Common.IModalInstance,
            private RoutingService: Routing.IRoutingService,
            private ControversyAlertPermissionsService: ControversyAlert.Security.IControversyAlertPermissionsService,
            public item: SubscribeToPortfolio) {

            var ctx = this;
            
            if (ctx.$rootScope['userInfo'] == null) {
                ctx.$rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }
            ctx.accountId = ctx.$rootScope['userInfo'].accountId;
            ctx.userId = ctx.$rootScope['userInfo'].userId;
            $scope['subscription'] = ctx;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();

            ctx.selectedPortfolios = new Array();
            ctx.allPortfolios = new Array();

            //semimonthly
            var semimonthlyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'POST', resource: 'api/v1/subscribetoportfolio', parameters: [{ key: 'alert', value: 'semimonthly' }] });
            var semimonthlyPromise = ctx.RoutingService.validateRouteSecurity(semimonthlyRouteSecurity);
            semimonthlyPromise.then(val => {
                this.hasSemimonthlyClaim = val;
            });

            ////monthly
            //var monthlyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'POST', resource: 'api/v1/subscribetoportfolio', parameters: [{ key: 'alert', value: 'monthly' }] });
            //var monthlyPromise = ctx.RoutingService.validateRouteSecurity(monthlyRouteSecurity);
            //monthlyPromise.then(val => {
            //    this.hasMonthlyClaim = val;
            //});

            ////quarterly
            //var quarterlyRouteSecurity = new Routing.RouteSecurity().addResource({ verb: 'POST', resource: 'api/v1/subscribetoportfolio', parameters: [{ key: 'alert', value: 'quarterly' }] });
            //var quarterlyPromise = ctx.RoutingService.validateRouteSecurity(quarterlyRouteSecurity);
            //quarterlyPromise.then(val => {
            //    this.hasQuarterlyClaim = val;
            //});

            ctx.hasEditPermission = ctx.ControversyAlertPermissionsService.hasControversyAlert();

            ctx.isAdd = false;
            ctx.clickSave = false;

            if (ctx.item == null) {
                ctx.isAdd = true;
                ctx.item = new SubscribeToPortfolio();
                ctx.item.frequency = 1;
                ctx.item.userId = ctx.userId;
                ctx.item.accountId = ctx.accountId;
                ctx.item.enabled = true;
                ctx.item.portfolioIds = new Array();
            }
            else {
                ctx.oldItem = new SubscribeToPortfolio();
                ctx.oldItem.frequency = ctx.item.frequency;
                ctx.oldItem.portfolioIds = ctx.item.portfolioIds;
                ctx.oldItem.enabled = ctx.item.enabled;
            }

            ctx.myEvents = {
                onMultiSelectBlur: function () {
                    ctx.haveSharedPortfolios();
                }
            };
            ctx.initMultiSelectPortfolios();
        }

        public haveSharedPortfolios() {
            var ctx = this;
            ctx.sharedPortfolios = false;
            for (var i = 0; i < ctx.allPortfolios.length; i++) {
                if (ctx.allPortfolios[i].group == "SharedPortfolio") {
                    for (var j = 0; j < ctx.selectedPortfolios.length; j++) {
                        if (ctx.allPortfolios[i].id == ctx.selectedPortfolios[j].id)
                            ctx.sharedPortfolios = true;
                    }
                }
            }
        }

        public cancel = function () {
            var ctx = this;
            //if (ctx.clickSave)
            //    ctx.$modalInstance.close({ currentItem: ctx.item });
            //else
            //    ctx.$modalInstance.close({ currentItem: ctx.oldItem });
            ctx.$modalInstance.close(/*{ currentItem: ctx.oldItem }*/);
        };

        public enabledSubscription() {
            var ctx = this;
            ctx.item.enabled = true;
        }

        public disabledSubscription() {
            var ctx = this;
            ctx.item.enabled = false;
        }

        public addEditAlert() {
            var ctx = this;
            ctx.item.userId = ctx.userId;
            ctx.item.accountId = ctx.accountId;
            ctx.item.portfolioIds = new Array();

            ctx.selectedPortfolios.forEach(item => {
                ctx.item.portfolioIds.push(item.id);
            });

            if (ctx.isAdd) {
                var promiseAddSubscribe =
                    ctx.SubscribeToPortfolioService.insertSubscription(ctx.item);
                promiseAddSubscribe.then(function () {
                    ctx.clickSave = true;
                    ctx.cancel();
                });
            }
            else {
                var promiseAddSubscribe =
                    ctx.SubscribeToPortfolioService.editSubscription(ctx.item);
                promiseAddSubscribe.then(function () {
                    ctx.clickSave = true;
                    ctx.cancel();
                });
            }
        }


        public getPortfolioType(portfolio: any): number{
            if (portfolio.addedByUserId === this.userId && (!portfolio.isAutomatic)) {
                return 0;
            }

            if (portfolio.isAutomatic)
                return 1;

            return 2;
        }

        public initMultiSelectPortfolios() {
            var ctx = this;


            var selectedPortfoliosTemp = new Array();
            var allPortfoliosTemp = new Array();

            if (ctx.isAdd === false && ctx.item.portfolioIds != null) {
                ctx.item.portfolioIds.forEach(id => {
                    var newPortfolio = {
                        id: id
                    };
                    selectedPortfoliosTemp.push(newPortfolio);
                });
            }
            

            //get all shared portfolios (send userId and accountId)
            var promise = ctx.SubscribeToPortfolioService.getSharedAndMyPortfolios(ctx.userId, ctx.accountId);
            promise
                .then(data => {

             

                var myPortfolios = {
                    id: "00000000-0000-0000-0000-000000000001",
                    name: "My portfolios",
                    type:0, //custom private
                    children: new Array()
                };

                var systemPortfolios = {
                    id: "00000000-0000-0000-0000-000000000002",
                    name: "System portfolios",
                    type: 1,
                    children: new Array()
                };
                var sharedPortfolios = {
                    id: "00000000-0000-0000-0000-000000000003",
                    name: "Shared portfolios",
                    type: 2,
                    children: new Array()
                };
                var allCompanies = {
                    id: "00000000-0000-0000-0000-000000000000",
                    name: AddEditSubscriptionController.allCompaniesLabel,
                    type: -1,
                };

                allPortfoliosTemp.push(allCompanies);

                allPortfoliosTemp.push(myPortfolios);

                allPortfoliosTemp.push(sharedPortfolios);

                allPortfoliosTemp.push(systemPortfolios);

                var portfolios: PortfolioDto[] = data["portfolioList"];

                portfolios.forEach(item => {

                    var parent = allPortfoliosTemp.filter(parentItem => (parentItem.type === this.getPortfolioType(item)));
                    parent[0].children.push(item);
                });
               
            });

            // after get and count are resolved set controller properties
            var promiseAll = ctx.$q.all([promise]);
            promiseAll.then(function () {
                ctx.allPortfolios = allPortfoliosTemp;
                allPortfoliosTemp.forEach(function (item) {
                    if (item.children != undefined) {
                        item.children.forEach(function (child) {
                            selectedPortfoliosTemp.forEach(function (selected) {
                                if (child.id === selected.id) {
                                    child.selected = true;
                                    ctx.selectedPortfolios.push(child);
                                }
                            });
                        });
                    }
                    else if (item.id === "00000000-0000-0000-0000-000000000000") {
                        if (selectedPortfoliosTemp.filter(p => p.id === "00000000-0000-0000-0000-000000000000").length==1) {
                            item.selected = true;
                            item.name = AddEditSubscriptionController.allCompaniesLabel;
                            ctx.selectedPortfolios.push(item);
                        }
                    }
                });

                //ctx.selectedPortfolios = selectedPortfoliosTemp;


                ctx.haveSharedPortfolios();
            });

            return promiseAll;
        }
    }

    // register controller with Portfolio Angular module
    angular.module(portfolioModuleName).controller('AddEditSubscriptionController',
        ['$rootScope', '$scope', '$q', 'SubscribeToPortfolioService', 'notificationFactory', '$modalInstance', 'RoutingService', 'ControversyAlertPermissionsService', 'item', AddEditSubscriptionController]);
}